package org.apache.tapestry5.csrfprotection.victimapp.pages;

import java.security.SecureRandom;
import java.util.Date;

import org.apache.tapestry5.ValueEncoder;
import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.annotations.InjectComponent;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.csrfprotection.CsrfProtected;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;
import org.slf4j.Logger;

import util.AuthenticationState;
import util.History;
import util.StatusMessage;

@CsrfProtected
public class Status {
	@Inject
	private Logger logger;

	@Property
	private String message;

	@SessionState(create = true)
	@Property
	private History history;

	@Property
	private StatusMessage _statusMessage;

	@Inject
	private Request request;

	@CsrfProtected
	private Object onSuccess() {
		StatusMessage statusMessage = new StatusMessage(message, new Date(),
				auth.getUserName());

		history.getLastMessages().add(statusMessage);
		return this;
	}

	@SessionState
	private AuthenticationState auth;

	@InjectPage
	private Index home;

	@Log
	private Object onActivate() {
		if (!auth.isLoggedIn()) {
			return home;
		}
		if (history.getLastMessages().size() == 0){
			for(int i=0; i< 10; i++){
				SecureRandom random = new SecureRandom();			
				StatusMessage message = new StatusMessage("" + random.nextLong(),new Date(), "test");
				history.getLastMessages().add(message);
			}
		}	
		return null;
	}

	@InjectComponent
	private Form statusForm;

	@CsrfProtected
	void onActionFromDelete(String msgId) {
		history.getLastMessages().remove(new StatusMessage(msgId));
		logger.debug("Delete called!");
	}

	@SuppressWarnings("rawtypes")
	public ValueEncoder getEncoder() {
		return new ValueEncoder<StatusMessage>() {

			public String toClient(StatusMessage value) {
				return value.getId();
			}

			public StatusMessage toValue(String keyAsString) {
				// not thread safe
				if (history.getLastMessages().contains(
						new StatusMessage(keyAsString))) {
					int index = history.getLastMessages().indexOf(
							new StatusMessage(keyAsString));
					return history.getLastMessages().elementAt(index);
				}

				throw new IllegalArgumentException("Received key \""
						+ keyAsString
						+ "\" which has no counterpart in this collection: "
						+ history.getLastMessages());
			}
		};
	}
		
	Object onAddRowFromAjaxStati() {
		return new StatusMessage();
	}


}
